package com.idlecode.panel;

import java.sql.SQLException;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.PlatformUI;
import com.idlecode.bean.DataSourceEntity;
import com.idlecode.config.GenDataSource;
import com.idlecode.manage.DataSourceFormManage;
import com.idlecode.service.DataSourceService;
import com.idlecode.util.MessageDialogUtil;
import cn.hutool.core.util.StrUtil;

/**
 * @program: IdleCode
 * @description
 * @author: rongjuwei
 * @create: 2024-02-05 17:06
 **/
public class DataSourcesPanel extends Composite {
	private Table table;

	public DataSourcesPanel(Composite parent, int style) {
		super(parent, style);

		setLayout(new GridLayout(1, false));

		Composite buttonComposite = new Composite(this, SWT.NONE);
		buttonComposite.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false));
		GridLayout buttonLayout = new GridLayout(5, true);
		buttonComposite.setLayout(buttonLayout);

		Button testBtn = new Button(buttonComposite, SWT.PUSH);
		testBtn.setText("测试");
		testBtn.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));

		Button addBtn = new Button(buttonComposite, SWT.PUSH);
		addBtn.setText("新增");
		addBtn.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));

		Button deleteBtn = new Button(buttonComposite, SWT.PUSH);
		deleteBtn.setText("删除");
		deleteBtn.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));

		Button editBtn = new Button(buttonComposite, SWT.PUSH);
		editBtn.setText("编辑");
		editBtn.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));

		Button queryBtn = new Button(buttonComposite, SWT.PUSH);
		queryBtn.setText("查询");
		queryBtn.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));

		// 添加按钮点击事件监听器
		testBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				int selectedRow = table.getSelectionIndex();
				if (selectedRow != -1) { // 判断是否有选中的行
					List<DataSourceEntity> dataSources = DataSourceService.getDataSources();
					DataSourceEntity dataSourceEntity = dataSources.get(selectedRow);
					GenDataSource genDataSource = null;
					try {
						genDataSource = new GenDataSource(dataSourceEntity);
						if (genDataSource.getConnection() == null) {
							MessageDialogUtil.showMessage("提示", "连接失败，网络异常！");
						} else {
							MessageDialogUtil.showMessage("提示", "连接成功！");
						}
					} catch (Exception exception) {
						MessageDialogUtil.showError("异常", StrUtil.format("连接失败！{}", exception.getMessage()));
					} finally {
						try {
							if (genDataSource.getConnection() != null) {
								genDataSource.getConnection().close();
							}
						} catch (SQLException ex) {
							MessageDialogUtil.showError("异常", "连接关闭失败！");
						}
					}
				} else {
					MessageDialogUtil.showWarning("警告", "请先选中数据源再点击测试按钮！");
				}
			}

		});

		addBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
				DataSourceFormManage dataSourceFormManage = new DataSourceFormManage(shell, DataSourcesPanel.this);
				dataSourceFormManage.open();
			}

		});

		deleteBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				int selectedRow = table.getSelectionIndex();
				if (selectedRow != -1) { // 判断是否有选中的行
					List<DataSourceEntity> dataSources = DataSourceService.getDataSources();
					dataSources.remove(selectedRow);
					// 删除选中的行
					table.remove(selectedRow);
					DataSourceService.setDataSources(dataSources);
				} else {
					MessageDialogUtil.showWarning("警告", "请先选中数据源再点击删除按钮！");
				}
			}
		});

		editBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				int selectedRow = table.getSelectionIndex();
				if (selectedRow != -1) { // 判断是否有选中的行
					List<DataSourceEntity> dataSources = DataSourceService.getDataSources();
					DataSourceEntity dataSourceEntity = dataSources.get(selectedRow);
					Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
					DataSourceFormManage dataSourceFormManage = new DataSourceFormManage(shell, selectedRow,
							dataSourceEntity.getConnName(), dataSourceEntity.getDbType(), dataSourceEntity.getConnUrl(),
							dataSourceEntity.getUsername(), dataSourceEntity.getPassword(), DataSourcesPanel.this);
					dataSourceFormManage.open();
				} else {
					MessageDialogUtil.showWarning("警告", "请先选中数据源再点击编辑按钮！");
				}
			}
		});

		queryBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				queryBtnAction();
			}
		});

		// 列表显示

		table = new Table(this, SWT.BORDER | SWT.FULL_SELECTION);
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		TableColumn connectionNameColumn = new TableColumn(table, SWT.NONE);
		connectionNameColumn.setText("连接名");

		TableColumn databaseTypeColumn = new TableColumn(table, SWT.NONE);
		databaseTypeColumn.setText("数据库类型");

		TableColumn databaseUrlColumn = new TableColumn(table, SWT.NONE);
		databaseUrlColumn.setText("数据库URL");

		// 添加一个监听器，在表格调整大小时动态调整列宽
		table.addControlListener(new ControlAdapter() {
			@Override
			public void controlResized(ControlEvent e) {
				int tableWidth = table.getClientArea().width;
				connectionNameColumn.setWidth((int) (tableWidth * 0.25)); // 30%
				databaseTypeColumn.setWidth((int) (tableWidth * 0.15)); // 40%
				databaseUrlColumn.setWidth((int) (tableWidth * 0.6)); // 30%
			}
		});

		List<DataSourceEntity> dataSourcesRows = DataSourceService.getDataSources();
		for (DataSourceEntity dataSourcesRow : dataSourcesRows) {
			// 添加数据行
			new TableItem(table, SWT.NONE).setText(new String[] { dataSourcesRow.getConnName(),
					dataSourcesRow.getDbType(), dataSourcesRow.getConnUrl() });
		}

	}

	public void queryBtnAction() {
		table.removeAll();
		List<DataSourceEntity> dataSourcesRows = DataSourceService.getDataSources();
		for (DataSourceEntity dataSourcesRow : dataSourcesRows) {
			// 添加数据行
			new TableItem(table, SWT.NONE).setText(new String[] { dataSourcesRow.getConnName(),
					dataSourcesRow.getDbType(), dataSourcesRow.getConnUrl() });
		}
	}
}
